#include "admin_dialog.h"
#include "info_dialog.h"
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QLabel>
#include <QPushButton>
#include <QApplication>
#include <QDebug>

AdminDialog::AdminDialog(QWidget *parent) : QDialog(parent), keyProcessing(false)
{
    setWindowTitle("管理员登录");
    setWindowFlags(Qt::Dialog | Qt::FramelessWindowHint);
    setWindowState(Qt::WindowFullScreen);
    QVBoxLayout *layout = new QVBoxLayout(this);

    // 创建标题栏布局
    QHBoxLayout *titleLayout = new QHBoxLayout();
    QLabel *titleLabel = new QLabel("管理员登录", this);
    titleLabel->setStyleSheet("QLabel { font-size: 24px; font-weight: bold; }");

    // 创建返回按钮
    QPushButton *backButton = new QPushButton("返回", this);
    backButton->setStyleSheet("QPushButton { font-size: 18px; padding: 8px 16px; }");
    connect(backButton, &QPushButton::clicked, this, &QDialog::reject);

    titleLayout->addWidget(titleLabel);
    titleLayout->addStretch();
    titleLayout->addWidget(backButton);

    layout->addLayout(titleLayout);
    layout->addSpacing(20);

    QLabel *userLabel = new QLabel("账号：", this);
    QLabel *pwdLabel = new QLabel("密码：", this);

    userEdit = new QLineEdit(this);
    userEdit->setPlaceholderText("请输入账号");
    userEdit->setFocusPolicy(Qt::StrongFocus);
    userEdit->setMinimumHeight(100);
    userEdit->setStyleSheet("font-size:56px;");

    pwdEdit = new QLineEdit(this);
    pwdEdit->setPlaceholderText("请输入密码");
    pwdEdit->setEchoMode(QLineEdit::Password);
    pwdEdit->setFocusPolicy(Qt::StrongFocus);
    pwdEdit->setMinimumHeight(100);
    pwdEdit->setStyleSheet("font-size:56px;");

    // 创建状态标签用于显示错误信息
    statusLabel = new QLabel(this);
    statusLabel->setStyleSheet("QLabel { color: red; }"); // 红色文字
    statusLabel->setAlignment(Qt::AlignCenter);
    statusLabel->hide(); // 初始隐藏

    // 使用单例获取键盘实例
    keyboard = KeyboardManager::getInstance().getKeyboard(this);
    keyboard->setFocusPolicy(Qt::NoFocus); // 防止键盘获取焦点

    // 初始化防抖定时器
    debounceTimer = new QTimer(this);
    debounceTimer->setSingleShot(true);
    debounceTimer->setInterval(50);

    // 连接定时器信号以重置防抖状态
    connect(debounceTimer, &QTimer::timeout, this, [this]()
            { keyProcessing = false; });

    // 连接键盘信号到输入框
    connect(keyboard, &Keyboard::keyPressed, [=](int key, QString value)
            {
        // 防抖处理
        if (keyProcessing) return;
        keyProcessing = true;
        debounceTimer->start();
        
        // 当有键盘输入时，隐藏错误状态
        statusLabel->hide();
        
        QWidget *focusWidget = QApplication::focusWidget();
        if (focusWidget && qobject_cast<QLineEdit*>(focusWidget)) {
            QLineEdit *lineEdit = qobject_cast<QLineEdit*>(focusWidget);
            
            // 特殊按键处理
            if (key == Qt::Key_Backspace) {
                lineEdit->backspace();
            } else if (key == Qt::Key_Enter || key == Qt::Key_Return) {
                // 按Enter键时切换焦点或确认
                if (lineEdit == userEdit)
                    pwdEdit->setFocus();
                else if (lineEdit == pwdEdit)
                    loginBtn->click(); // 在密码框按Enter触发登录
            } else {
                // 普通文本输入
                lineEdit->insert(value);
            }
        } });

    loginBtn = new QPushButton("登录", this);
    loginBtn->setStyleSheet("QPushButton { font-size: 18px; padding: 8px 16px; }");

    layout->addWidget(userLabel);
    layout->addWidget(userEdit);
    layout->addWidget(pwdLabel);
    layout->addWidget(pwdEdit);
    layout->addWidget(statusLabel); // 添加状态标签
    layout->addWidget(keyboard);    // 添加键盘到布局

    // 创建底部按钮布局
    QHBoxLayout *buttonLayout = new QHBoxLayout();
    buttonLayout->addStretch();
    buttonLayout->addWidget(loginBtn);
    layout->addLayout(buttonLayout);

    // 设置初始焦点
    userEdit->setFocus();

    // 设置对话框大小
    resize(600, 500);

    // 登录按钮处理
    connect(loginBtn, &QPushButton::clicked, this, [=]()
            {
        static bool isProcessing = false;
        if (isProcessing) return;
        isProcessing = true;
        QTimer::singleShot(300, [=]() { isProcessing = false; });

        if (userEdit->text() == "admin" && pwdEdit->text() == "1234567") {
            // 登录成功，弹出信息录入对话框
            InfoDialog infoDialog(this);
            infoDialog.setWindowTitle("信息录入");
            infoDialog.exec();

            accept(); // 关闭管理员登录对话框
        } else {
            statusLabel->setText("账号或密码错误！");
            statusLabel->show();
            pwdEdit->clear();
            pwdEdit->setFocus();
            QTimer::singleShot(3000, statusLabel, &QLabel::hide);
        } });
}

AdminDialog::~AdminDialog()
{
    // 归还键盘到永久容器
    KeyboardManager::getInstance().releaseKeyboard();
}

void AdminDialog::showEvent(QShowEvent *event)
{
    QDialog::showEvent(event);

    // 确保键盘正确显示
    if (keyboard && !keyboard->isVisible())
    {
        keyboard->show();
    }

    // 重新设置焦点
    QTimer::singleShot(100, [this]()
                       { userEdit->setFocus(); });
}

void AdminDialog::closeEvent(QCloseEvent *event)
{
    // 释放键盘回永久容器
    KeyboardManager::getInstance().releaseKeyboard();
    QDialog::closeEvent(event);
}